package com.fjnu.dao.impl;

import com.fjnu.dao.UserDao;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int insert(User user) {
        String sql = "INSERT INTO tb_user (name,password,salt,create_time,gender,score,status,email) VALUES (?,?,?,?,?,?,?,?)";
        int result = jdbcTemplate.update(sql,
                user.getName(),
                user.getPassword(),
                user.getSalt(),
                user.getCreateTime(),
                user.getGender(),
                user.getScore(),
                user.getStatus(),
                user.getEmail());
                return result > 0 ? 1 : 0;
    }

    @Override
    public int insertUserRole(Integer userId, Integer roleId) {
        String sql = "INSERT INTO tb_user_role (user_id,role_id) VALUES (?,?)";
        int result = jdbcTemplate.update(sql,userId,roleId);
        return result > 0 ? 1 : 0;
    }

    @Override
    public int batchInsertUserRoles(Integer userId, List<Integer> roleIds) {
        int count=0;
        for (Integer roleId : roleIds) {
            int i = insertUserRole(userId, roleId);
            count += i;
        }
        return count;
    }

    @Override
    public int updatePassword(Integer userId, String newPassword) {
        String sql = "UPDATE tb_user SET password = ? WHERE user_id = ?";
        int result = jdbcTemplate.update(sql, newPassword, userId);
        return result > 0 ? 1 : 0;
    }

    @Override
    public int updateScore(Integer userId, Long incremetedScore) {
        String sql = "UPDATE tb_user SET score = score + ? WHERE user_id = ?";
        int result = jdbcTemplate.update(sql, incremetedScore, userId);
        return result > 0 ? 1 : 0;
    }

    @Override
    public User selectByNameAndPwd(String username, String password) {
        String sql = "SELECT * FROM tb_user WHERE name = ? AND password = ?";
        return jdbcTemplate.queryForObject(sql, new UserRowMapper(), username, password);
    }

    @Override
    public List<User> selectByCondition(UserConditionDto userConditionDto) {
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM tb_user WHERE 1=1");
        if (userConditionDto.getUserId() != null) {
            sqlBuilder.append(" AND user_id = ").append(userConditionDto.getUserId());
        }
        if (userConditionDto.getName() != null) {
            sqlBuilder.append(" AND name = '").append(userConditionDto.getName()).append("'");
        }
        if (userConditionDto.getEmail() != null) {
            sqlBuilder.append(" AND email = '").append(userConditionDto.getEmail()).append("'");
        }
        if (userConditionDto.getGender()!= null) {
            sqlBuilder.append(" AND gender = ").append(userConditionDto.getGender());
        }
        if (userConditionDto.getScore() != null) {
            sqlBuilder.append(" AND score = ").append(userConditionDto.getScore());
        }
        sqlBuilder.append(" LIMIT 1");
        return jdbcTemplate.query(sqlBuilder.toString(), new UserRowMapper());

    }


    @Override
    public List<User> selectByConditionWithLimit(UserConditionDto UserConditionDto, Integer startIndex, Integer endIndex) {
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM tb_user WHERE 1=1");
        if (UserConditionDto.getUserId() != null) {
            sqlBuilder.append(" AND user_id = ").append(UserConditionDto.getUserId());
        }
        if (UserConditionDto.getName() != null) {
            sqlBuilder.append(" AND name = '").append(UserConditionDto.getName()).append("'");
        }
        if (UserConditionDto.getEmail() != null) {
            sqlBuilder.append(" AND email = '").append(UserConditionDto.getEmail()).append("'");
        }
        if (UserConditionDto.getGender()!= null) {
            sqlBuilder.append(" AND gender = ").append(UserConditionDto.getGender());
        }
        if (UserConditionDto.getScore() != null) {
            sqlBuilder.append(" AND score = ").append(UserConditionDto.getScore());
        }
        sqlBuilder.append(" LIMIT ").append(startIndex).append(",").append(endIndex);
        return jdbcTemplate.query(sqlBuilder.toString(), new UserRowMapper());

    }
    private static class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setUserId(rs.getInt("user_id"));
            user.setName(rs.getString("name"));
            user.setPassword(rs.getString("password"));
            user.setSalt(rs.getString("salt"));
            user.setCreateTime(rs.getDate("create_time"));
            user.setGender(rs.getInt("gender"));
            user.setScore(rs.getInt("score"));
            user.setStatus(rs.getInt("status"));
            user.setEmail(rs.getString("email"));
            return user;
        }
    }
}
